package com.blockchain.securewallet.activities;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.MainActivity;
import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.adapter.AccountManagerAdapter;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.manager.ThreadPoolManager;
import com.blockchain.securewallet.model.db.Account;
import com.blockchain.securewallet.model.db.CoinWallet;
import com.blockchain.securewallet.model.db.oper.AccountDaoOpe;
import com.blockchain.securewallet.tools.ActivityLauncher;
import com.blockchain.securewallet.tools.SpaceItemDecoration;
import com.blockchain.securewallet.tools.WeakHandler;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.ShowPopUtil;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.ToastUtils;
import com.blockchain.securewallet.utils.ToolUtils;
import com.blockchain.securewallet.utils.UIHelper;

import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Chain-Cloud on 2018/6/8.
 */

public class AccountManagerActivity extends BaseActivity implements AccountManagerAdapter.ISwitchAccountListener {

    @BindView(R.id.tv_current_account)
    TextView tv_current_account;
    @BindView(R.id.rv_account_history)
    RecyclerView rv_account_history;
    @BindView(R.id.tv_switch_to_new)
    TextView tv_switch_to_new;
    @BindView(R.id.tv_title)
    TextView tv_title;


    private AccountManagerAdapter accountManagerAdapter;
    private List<Account> coinWalletList = new ArrayList<>();
    private ShowPopUtil showPopUtil;

    private CoinWallet etherWallet = null;
    private CoinWallet bitCoinWallet = null;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_manager);
        ButterKnife.bind(this);

        tv_title.setText(getString(R.string.account_manager));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取所有历史账号

        coinWalletList = AccountDaoOpe.queryAll(this);

        int idLength = coinWalletList.get(coinWalletList.size() - 1).getAccountId().length();
        tv_current_account.setText(coinWalletList.get(0).getAccountId().substring(idLength - 4, idLength));

        accountManagerAdapter = new AccountManagerAdapter(this, coinWalletList);
        accountManagerAdapter.setListener(this);

        rv_account_history.setLayoutManager(new LinearLayoutManager(this));
        rv_account_history.addItemDecoration(new SpaceItemDecoration(UIHelper.dipToPx(3.0f), true));
        rv_account_history.setAdapter(accountManagerAdapter);

    }

    @OnClick(R.id.tv_switch_to_new)
    void newAccount() {
//        Intent intent = new Intent();
//        intent.setClass(this, WalletInitActivity.class);
//        startActivity(intent);
        ActivityLauncher.gotoWalletInitActivity(this, false);
    }

    @Override
    public void onClick(final Account account) {
        String curId = account.getAccountId();
        Account user = WalletApp.queryCurrrentAccount();

        if (user != null) {
            if (user.getAccountId().equals(curId)) {
                ToastUtils.showToast("已经是当前的钱包了");
                return;
            }
        }

        if (showPopUtil == null) {
            //首先弹出密码输入框
            showPopUtil = new ShowPopUtil(R.layout.password_ensure_dialog, AccountManagerActivity.this, 0.7, 0.3) {

                @Override
                protected void initView(View view) {

                    final EditText edit_first_password = view.findViewById(R.id.edit_first_password);
                    TextView tv_cancel = view.findViewById(R.id.tv_cancel);
                    TextView tv_ok = view.findViewById(R.id.tv_ok);

                    tv_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPopUtil.dismiss();
                            showPopUtil = null;
                        }
                    });
                    tv_ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (!edit_first_password.getText().toString().equals(account.getPayPassword())) {
                                ToastUtils.showToast("密码错误");

                            } else {
                                //切换账号
                                generateWalletAsync(account.getPayPassword(), account.getMemorizing_words(), account);
                                showPopUtil.dismiss();
                                showPopUtil = null;
                            }

                        }
                    });
                }
            }; 
        }

        showPopUtil.showPop();
    }

    //删除对应账户
    @Override
    public void onDelete(final int position, final Account account) {
        String curId = account.getAccountId();
        Account user = WalletApp.queryCurrrentAccount();

        if (user != null) {
            if (user.getAccountId().equals(curId)) {
                ToastUtils.showToast("不能删除当前账户！");
                return;
            }
        }
        
        //弹出删除确认的弹窗
        showInputDialog(position, account);
    }


    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }


    private void generateWalletAsync(final String password, final String strCode, final Account oldAccount) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... voids) {
//                WalletApp.getInstance().getDaoSession().getUnSpentDao().deleteAll();
//                createWallet(password,strCode);

                List<CoinWallet> coinWallets = new ArrayList<>();
                coinWallets.addAll(oldAccount.getCoinWalletList());
                Account account = new Account();
                account.setAccountId(oldAccount.getAccountId());
                account.setPayPassword(password);
                account.setTime(System.currentTimeMillis());
                account.setMemorizing_words(strCode);
                account.setCoinWalletList(coinWallets);
                AccountDaoOpe.insertData(AccountManagerActivity.this, account);
                //删除上一条记录
                AccountDaoOpe.deleteData(AccountManagerActivity.this, oldAccount);


//                WalletApp.getInstance().getDaoSession().insert(bitCoinWallet);
//                WalletApp.getInstance().getDaoSession().insert(etherWallet);
//                WalletApp.getInstance().saveWordsList(strCode);
//                WalletApp.getInstance().savePayPassword(password);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                MainActivity.startFromWalletCreate(AccountManagerActivity.this);
                finish();
            }
        }.execute();
    }


    //避免内存泄漏的Handler的使用
    WeakHandler handler = new WeakHandler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    //删除动画
                    accountManagerAdapter.notifyItemRemoved(msg.arg1);
                    // accountManagerAdapter.notifyItemChanged(msg.arg1);
                    break;
                case 1:
                    //删除结果
                    ToastUtils.showToast("删除成功！");
                    //accountManagerAdapter.notifyItemRemoved(msg.arg1);
                    //accountManagerAdapter.notifyItemChanged(msg.arg1);
                    accountManagerAdapter.notifyDataSetChanged();
                    break;
            }

            //不需要继续处理msg了
            return true;
        }
    });


    //弹窗确认是否删除账号
    void showInputDialog(final int position, final Account account) {
        //首先弹出密码输入框
        if (showPopUtil == null) {
            showPopUtil = new ShowPopUtil(R.layout.password_ensure_dialog, AccountManagerActivity.this, 0.7, 0.3) {

                @Override
                protected void initView(View view) {

                    final EditText edit_first_password = view.findViewById(R.id.edit_first_password);
                    TextView tv_cancel = view.findViewById(R.id.tv_cancel);
                    TextView tv_ok = view.findViewById(R.id.tv_ok);
                    final TextView tv_tips_pw_err = view.findViewById(R.id.tv_tips_pw_err);

                    edit_first_password.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                            //Logger.ds("beforeTextChanged.");
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                            //如果显示了，就隐藏掉；如果隐藏了，就别管。
                            if (tv_tips_pw_err.getVisibility() == View.VISIBLE) {
                                //Logger.ds("onTextChanged 显示了，隐藏掉.");
                                tv_tips_pw_err.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            //Logger.ds("afterTextChanged.");
                        }
                    });

                    tv_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            showPopUtil.dismiss();
                            showPopUtil = null;
                        }
                    });

                    tv_ok.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!edit_first_password.getText().toString().equals(WalletApp.getInstance().getPayPassword())) {

                                if (StringUtil.isEmpty(edit_first_password.getText().toString())) {
                                    tv_tips_pw_err.setText(getString(R.string.tips_password_null));
                                } else {
                                    tv_tips_pw_err.setText(getString(R.string.tips_password_error));
                                }

                                tv_tips_pw_err.setVisibility(View.VISIBLE);

                            } else {
                                //密码正确后，放行
                                doDelete(position, account);

                                showPopUtil.dismiss();
                                showPopUtil = null;
                            }

                        }
                    });

                }
            };
        }

        showPopUtil.showPop();
    }

    
    //执行删除账号操作
    private void doDelete(final int position, final Account account) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //删除当前记录
                AccountDaoOpe.deleteData(AccountManagerActivity.this, account);
                //重新赋值，使得notifyDataSetChanged刷新生效
                handler.sendEmptyMessage(0);

                // 不能直接使用=号，使用=号会使地址重新变更，只能在原地址上发生数据的改变
                coinWalletList.clear();
                coinWalletList.addAll(AccountDaoOpe.queryAll(AccountManagerActivity.this));

                //获取新的or已存在的Message
                Message message = Message.obtain();
                message.what = 1;
                message.arg1 = position;
                handler.sendMessage(message);
            }
        };

        ThreadPoolManager.execute(runnable);
    }


}
